<?php

namespace app\api\model;

use app\admin\model\gift\Goods;
use app\admin\model\goods\GoodsModel;
use app\admin\model\Mail;
use app\common\model\ScoreLog;
use app\common\model\User;
use think\Exception;
use think\Model;

class Order extends Model
{
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
        'expire_time_text',
    ];

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['create_time'] ?? "");
        return is_numeric($value) ? date("d F Y H:i:s", $value) : $value;
    }

    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['update_time'] ?? "");
        return is_numeric($value) ? date("d F Y H:i:s", $value) : $value;
    }

    public function getexpireTimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['expire_time'] ?? "");
        return is_numeric($value) ? date("d F Y H:i:s", $value) : $value;
    }


    /**
     * Notes: 查询可用的优惠券列表
     * User: chenLei
     * Date: 8/17/25
     * @param $params
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function list($params)
    {
        $user = User::where('username', $params['username'])->find();
        if (empty($user)) {
            $this->error = 'User error';
            return false;
        }

        $list = $this->where(['shop_id' => $params['shop_id'], 'user_id' => $user['id'],
            'is_use' => 0])->where('expire_time', '>', time())
            ->where('categorys_id', 'in', [1, 2])
            ->field('id,shop_id,user_id,categorys_id,goods_id,money,expire_time,is_use,create_time')
            ->order('categorys_id,money desc')
            ->select();

        foreach ($list as $value) {
            $value['goods'] = GoodsModel::where('id', $value['goods_id'])->field('id,name')->find();
            $value['expire_time'] = date('Y-m-d H:i:s', $value['expire_time']);
        }

        return $list;
    }


    /**
     * Notes: 周期检测是否有兑换商品
     * User: chenLei
     * Date: 8/26/25
     * @param $user_id
     * @param $type
     * @return int|string
     * @throws \think\Exception
     */
    public function checkCycle($user_id, $type = 'month')
    {

        $where = [];
        if ($type == 'month') {
            $startTime = strtotime(date('Y-m-01 00:00:00'));
            $endTime = strtotime(date('Y-m-t 23:59:59'));
            $where['categorys_id'] = ['=', 3];
        } else {
            $startTime = strtotime('monday this week 00:00:00');
            $endTime = strtotime('sunday this week 23:59:59');
            $where['categorys_id'] = ['=', 4];

        }
        $where['create_time'] = ['between time', [$startTime, $endTime]];
        $where['user_id'] = ['=', $user_id];
        $where['is_use'] = ['in', [0, 1]];
        return $this->where($where)
            ->count();
    }


    /**
     * Notes: 查询当月是否有 自动兑换生日礼物
     * User: chenLei
     * Date: 8/26/25
     * @param $user_id
     * @return int|string
     * @throws \think\Exception
     */
    public function checkBirthdayGoods($user_id)
    {
        $startTime = strtotime(date('Y-m-01 00:00:00'));
        $endTime = strtotime(date('Y-m-t 23:59:59'));

        return $this->where(['user_id' => $user_id, 'categorys_id' => 5])
            ->where('create_time', 'between time', [$startTime, $endTime])
            ->count();
    }


    /**
     * Notes: 发放生日礼物
     * User: chenLei
     * Date: 8/26/25
     * @param $user_id
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function birthday($user_id)
    {

        $res = Goods::where(['categorys_id' => 5])->find();

        if (!empty($res)) {
            $order_sn = createOrderNo();
            if ($res['validity']) {
                $expire_time = strtotime('+' . $res['validity'] . 'days');
            } else {
                $expire_time = strtotime('+10 year');
            }

            $order_data = [
                'order_sn' => $order_sn,
                'shop_id' => $res['shop_id'],
                'user_id' => $user_id,
                'goods_info' => json_encode($res, 256),
                'score' => $res['score'],
                'name' => $res['name'],
                'validity' => $res['validity'],
                'lables' => $res['lables'],
                'content' => $res['content'],
                'image' => $res['image'],
                'categorys_id' => $res['categorys_id'],
                'expire_time' => $expire_time ?? '',
                'create_time' => time(),
                'update_time' => time(),
                'qrcode' => (new \app\api\controller\User())->qrcode($order_sn),
            ];

            $this->insert($order_data);

            Mail::create([
                'title' => '🎉 Happy Birthday from Uncle Five Coffee 🎉',
                'subtitle' => 'Celebrate your special month with us!',
                'content' => 'As part of the Uncle Five Coffee family, you deserve a little extra joy. Enjoy your exclusive Birthday Voucher this month—our treat to you!

- Redeem this voucher in-store or via the app
- Valid throughout your birthday month
- One-time use only

Make your celebration sweeter with Uncle Five Coffee. Cheers to another amazing year ahead! ',
                'user_id' => $user_id,
                'type' => 1,
                'page_type' => 0,
                'jump' => 0,
                'shop_id' => 1,
            ]);

        }

        return true;
    }


    /**
     * Notes: 取消商品兑换
     * User: chenLei
     * Date: 9/17/25
     * @param $order_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function cancelExchange($order_id)
    {
        $order = $this->where('order_id', $order_id)->find();
        if (empty($order)) {
            $this->error = '订单信息不存在';
            return false;
        }

        if ($order['is_use'] != 0) {
            $this->error = '该订单状态不能撤销';
            return false;
        }

        $this->startTrans();
        try {
            $this->where('order_id', $order_id)->update([
                'is_use' => 2,
                'cancel_time' => time(),
            ]);

            $log = ScoreLog::where('order_id', $order_id)->where('status', ScoreLog::STATUS_GOODS)
                ->find();

            if (!empty($log)) {
                $user = User::where('id', $order['user_id'])->find();
                if (!empty($user)) {

                    $end_score = $user['score'] + $log['score'];
                    $before = $user['score'];
                    $user->score = $end_score;
                    $user->save();

                    ScoreLog::create([
                        'user_id' => $order['user_id'],
                        'score' => $log['score'],
                        'before' => $before,
                        'after' => $end_score,
                        'type' => 1,
                        'memo' => 'Order cancel',
                        'status' => ScoreLog::STATUS_GOODS_CANCEL,
                        'order_id' => $order_id
                    ]);
                }
            }

            $this->commit();
        } catch (Exception $exception) {
            $this->rollback();
            $this->error = $exception->getMessage();
            return false;
        }

        return true;

    }


    /**
     * Notes: 撤销 已核销的订单  改为待核销
     * User: chenLei
     * Date: 9/17/25
     * @param $order_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cancelVerificationOrder($order_id)
    {
        $order = $this->where('id', $order_id)->find();
        if (empty($order)) {
            $this->error = '订单信息不存在';
            return false;
        }

        if ($order['is_use'] != 1) {
            $this->error = '该订单状态不能撤销';
            return false;
        }

        $order->is_use = 0;
        $order->save();

        return true;
    }
}